package com.ssh.cp.service;



import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssh.cp.entity.User;
import com.ssh.cp.idao.ILibraryDao;
import com.ssh.cp.idao.IUserDao;
import com.ssh.cp.iservice.IUserService;

@Service  
@Transactional  
public class UserService implements IUserService{  
    @Resource  
    IUserDao userDao;  
    @Resource
    ILibraryDao libraryDao;
      
    public String addUser(User user) {
    	Timestamp createTime=new Timestamp(new Date().getTime());//设置注册时间
    	user.setCreateTime(createTime);
//    	DateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
//		Date d=new Date();
//		try {
//			d = sdf.parse(birth);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    	
//    	
//    	Timestamp birthday=new Timestamp(d.getTime());
//    	user.setBirthday(birthday);
    	if(userDao.existUserName(user.getUsername()))
    		return "用户已存在！"; 
    	else {
    	userDao.addUser(user);
		return "注册成功！";  
		}
    }  
    
    public List<?> login(User user) {
    	
    	return userDao.loginUser(user);
    }

	@Override
	public void updateUser(int userid,String birth,String nickname) {
		// TODO Auto-generated method stub
		User user=new User();
		DateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
		Date d=new Date();
		try {
			d = sdf.parse(birth);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Timestamp birthday=new Timestamp(d.getTime());
		
		Timestamp gmt_modified=new Timestamp(new Date().getTime()); //设置修改时间
		user.setUserid(userid);
		user.setGmt_modified(gmt_modified);
		user.setBirthday(birthday);
		user.setNickname(nickname);
		userDao.updateUser(user);
	}

	@Override
	public String changePassword(int userid, String oldpassword, String newpassword) {
		
		// TODO Auto-generated method stub
		if(userDao.checkPassword(userid, oldpassword)) {
			if(userDao.changePassword(userid, newpassword)) {
				return "密码修改成功";
			}else {
				return "密码修改失败";
			}
		}else {
			return "原密码不正确";
		}
		
		
	}

	@Override
	public List<?> listUser() {
		// TODO Auto-generated method stub
		/*List<?> list=userDao.listUser();
		int i=list.size();
		User[] u=(User[])list.toArray(new User[i]);
		
		System.out.println(u[0].getBirthday());
		List<?>us=Arrays.asList(u);*/
		return userDao.listUser();
	}

	
	

} 
